//
//  PhotoSelectViewController.m
//  WuliHanhan
//
//  Created by chen tang on 16/3/3.
//  Copyright © 2016年 LVpeng. All rights reserved.
//

#import "PhotoSelectViewController.h"
#import "Header.h"
#import "PhotoImageModel.h"
#import "DataBaseSaveEditeImageModel.h"
#import "PostUploadImageDataBase.h"



#import "PhotoCollectionViewCell.h"
#import "MyLayout.h"
#import "ImagePushButton.h"


#import "LOadImageView.h"

#import <PhotosUI/PhotosUI.h>
#import "UINavigationController+navantion.h"


//#import "CreatImageWithTextViewController.h"

#import "BaseCreatViewController.h"
#import "UserEditeImageViewController.h"

@interface PhotoSelectViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,
                                                                                                        PhotoCollectionViewCellDelegate,
                                                                                                        ImagePushButtonDelegate,
                                                                                                            BaseDataSource>





{
    
    NSMutableArray *sourceImageArray;

    ImagePushButton *imagePushButton;
    
    NSMutableArray *nameIndexArray;
//    NSMutableArray *yasuotuArray;   //添加选中压缩图
    
    LOadImageView *loadIMageView;
    
    int totlePhotoInt;
    int lastInt;
}

@property (strong, nonatomic)UICollectionView *collectionView;


@property (nonatomic, strong) NSMutableArray *imageArray;


@property (nonatomic, strong) NSMutableArray *selectImageMutableArray;


@end

@implementation PhotoSelectViewController



sloganIntence(PhotoSelectViewController);




- (void)loadView
{
    [super loadView];
    

    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    _imageArray = [NSMutableArray new];
    sourceImageArray = [NSMutableArray new];
    nameIndexArray = [NSMutableArray new];
    _selectImageMutableArray = [NSMutableArray new];
    
//    yasuotuArray = [NSMutableArray new];
    
    
    [self.navigationController setNavigationBarHidden:YES];
    
    
    UIView *titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WithView, 44.0)];
    [titleView setBackgroundColor:uicolor(254, 195, 9)];
    [self.view addSubview:titleView];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 12.5, WithView, 20.0)];
    [titleLable setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:titleLable];
    [titleLable setText:@"选择照片"];
    [titleLable setTextColor:uicolor(13, 20, 25)];
    
    
    
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    
    self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 46, WithView, heightView-104) collectionViewLayout:flowLayout];
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    //注册Cell，必须要有
    [self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    
    [self.view addSubview:self.collectionView];
    
    
    UIImage *image = nil;
    
    image = [UIImage imageNamed:@"quxiao.png"];
    
    UIButton *calcanButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    [calcanButton setBackgroundImage:image forState:UIControlStateNormal];
    [self.view addSubview:calcanButton];
    [calcanButton addTarget:self action:@selector(cancleToPopView) forControlEvents:UIControlEventTouchUpInside];
    
    

    imagePushButton = [[ImagePushButton alloc] initWithFrame:CGRectMake(0, 0, 64, 26)];
    [imagePushButton setCenter:CGPointMake(WithView-42.0, 22.0)];
    [imagePushButton setMImagePushButtonDelegate:self];
    [self.view addSubview:imagePushButton];
    
    [self addObserVweToCommit];
    
//    NSLog(@"loadview22222222222");
    

    loadIMageView = [[LOadImageView alloc] initWithFrame:CGRectMake(0, 0, WithView, WithView)];
    
//    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) {
//        
//        PHFetchResult *assetsLibrary = [[PHFetchResult alloc] init];
////        [assetsLibrary enumerateObjectsUsingBlock:<#^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)block#>]
//    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    [self.collectionView setAllowsMultipleSelection:YES];
    
    
    if (_plusImage)
    {
//        [nameIndexArray addObjectsFromArray:_nameIndexArray];
//        [yasuotuArray addObjectsFromArray:_imageYasuoArray];
    }
    else
    {
    //第一次进入
        [[DataBaseSaveEditeImageModel sharedInstance] openDataBase];
    }
    [[BaseCreatViewController sharedInstance] setMBaseDataSource:self];
}



- (void)addObserVweToCommit
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xiangceBeganReolad) name:imageSaveSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jiantingshumu:) name:@"boxshumu" object:nil];
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [self changeSelectJudge];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//选择照片数目
- (void)jiantingshumu:(NSNotification *)notion
{
//    totlePhotoInt = [[notion object] intValue]+totlePhotoInt;
    
    lastInt = [[notion object] intValue];
    
//    [imagePushButton    setNumberInt:totlePhotoInt+lastInt];
}




//接受返回图片
- (void)imagePostImageArray:(NSNotification *)notion
{
//    [imageSelectMutableArray removeAllObjects];
//    [imageSelectMutableArray addObjectsFromArray:[notion object]];
}





- (void)changeSelectJudge
{
    
    [_imageArray removeAllObjects];
    [sourceImageArray removeAllObjects];
    [nameIndexArray removeAllObjects];
//    [yasuotuArray removeAllObjects];

    
    
    [[PhotoImageModel sharedInstance] setSelectAtIndenx:0 WithCallBack:^(NSArray *array, NSArray *imageOrnArray){
        [_imageArray addObjectsFromArray:array];
        
        [sourceImageArray addObjectsFromArray:imageOrnArray];
    
    }];

}




//拍照保存成功刷新相册
- (void)xiangceBeganReolad
{
    [_imageArray removeAllObjects];
    [sourceImageArray removeAllObjects];
    [nameIndexArray removeAllObjects];
    
    
    [[DataBaseSaveEditeImageModel sharedInstance] updateDataBaseWithIndex];
    
    [[PhotoImageModel sharedInstance] setSelectAtIndenx:0 WithCallBack:^(NSArray *array, NSArray *imageOrnArray){
        [_imageArray addObjectsFromArray:array];
        
        [sourceImageArray addObjectsFromArray:imageOrnArray];
        
        
    }];

    
    [[DataBaseSaveEditeImageModel sharedInstance] rearDataBaseForPhotos:^(NSArray *nameArray, NSArray *dataArray){
        
        [nameIndexArray addObjectsFromArray:nameArray];
        [_collectionView reloadData];
    }];

}




//取消选择
- (void)cancleToPopView
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"addnewimage" object:imageSelectMutableArray];
//    NSLog(@"%@", _imageSelectMutableArray);
    // 列出所有相册智能相册
      
//    [BaseCreatViewController sharedInstance].arrayWithArray = yasuotuArray;
    if (_plusImage)
    {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"addphoto" object:_selectImageMutableArray];
    }
    else
    {
        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];


}


//进入创作
- (void)pushToCreatView
{
    
//    if (_plusImage)
//    {
//
//        [[PostUploadImageDataBase sharedInstance] addPhotoWithImageArray:_selectImageMutableArray withConnectIDArray:array];
//
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"addphoto" object:_selectImageMutableArray];
////        [self dismissViewControllerAnimated:YES completion:nil];
//        
////        [_MPhotoSelectViewControllerDelegate selectPhotoWithIMageArray:nil];
//    }
//    else
//    {
//        [[PostUploadImageDataBase sharedInstance] openDataBase];
//        
//        NSMutableArray *array = [NSMutableArray new];
//        
//        for (int i = 0; i < _selectImageMutableArray.count; i ++)
//        {
//            [array addObject:@"0"];
//        }
//        
//        [[PostUploadImageDataBase sharedInstance] insertModelwithImageArray:_selectImageMutableArray withCOnnectIDArray:array];
//        UserEditeImageViewController *editeVC = [[UserEditeImageViewController alloc] init];
//        editeVC.imageMutableArray = _selectImageMutableArray;
//        [self.navigationController pushViewController:editeVC animated:YES];
//
//     }
    [_MPhotoSelectViewControllerDelegate photoPUsh];
}

#pragma mark----从创作返回

- (void)getImageArray:(NSArray *)array
{
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_imageArray count];
}


//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    PhotoCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell setTag:indexPath.row];
    cell.dataImage = _imageArray[indexPath.row];
    [cell setMPhotoCollectionViewCellDelegate:self];
    [cell setModelWith:nameIndexArray];
    
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个Item 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(biliwith(77.0), biliwith(77.0));
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}



- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 4.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 4.0;
}



//cell代理
- (void)chooseImageWithIndex:(NSInteger)index withSelectBool:(BOOL)select
{
    
    if (select)
    {
        
            [[PhotoImageModel sharedInstance] selectAsset:sourceImageArray[index] getOrnImage:^(NSData *data){
                
                [_selectImageMutableArray addObject:data];
                
            }];
        
        [nameIndexArray addObject:[NSString stringWithFormat:@"%d", (int)index]];
        
    }
    else
    {

        [[PhotoImageModel sharedInstance] selectAsset:sourceImageArray[index] getOrnImage:^(NSData *data){
            
            [_selectImageMutableArray removeObject:data];
            
        }];
        
        //删除名字下标
        [nameIndexArray     removeObject:[NSString stringWithFormat:@"%d", (int)index]];
        
    }
    
    NSMutableArray *array = [NSMutableArray new];
    //
    for (int i = 0; i < _selectImageMutableArray.count; i ++)
    {
        [array addObject:@"0"];
    }

    [_MPhotoSelectViewControllerDelegate selectPhotoWithIMageArray:_selectImageMutableArray withConnectIDArray:array];
    
    
    totlePhotoInt = (int)[_selectImageMutableArray count];
    [imagePushButton    setNumberInt:totlePhotoInt];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
